#include "Game.h"
#include "Utils.h"
#include "Audio.h"

Game::Game() {
	scene = new Scene();
	controller = new Controller();
	camera = new Camera( 1024, 768, this );
}
Game::~Game() {
}

int Game::run()
{
	static unsigned long lastTime = 0;

	Audio::getInstance().playMusic();

	// Preload textures
	TextureLoader::getInstance().loadTexture( "textures/koopa.png" );
	TextureLoader::getInstance().loadTexture( "textures/goomba.png" );
	TextureLoader::getInstance().loadTexture( "textures/sario3.png" );
	TextureLoader::getInstance().loadTexture( "textures/castle.png" );
	TextureLoader::getInstance().loadTexture( "textures/prinses.png" );

	Texture youwin("textures/prinses.png");

	bool running = true;
	while ( running ) {

		unsigned long currentTime = SDL_GetTicks();
		float frametime = (currentTime - lastTime) / 1000.f;

		running &= controller->poll();
		if(controller->getKeyMap().reset){
			delete scene;
			scene = new Scene();
		}
		scene->getPlayer()->setMovementMap( controller->getKeyMap() );
	
		scene->update( frametime );
		camera->render( frametime );

		if(scene->getPlayer()->isDead()){
			camera->drawText(Position(2,2), "Game over");
			camera->drawText(Position(2,-3), "Press space to restart");
		}else if(scene->getPlayer()->hasWon())
		{
			glColor3f(1,1,1);
			youwin.bind();
			glBegin(GL_QUADS);
			glTexCoord2f(0.f,0.f); glVertex2f( -55.f, -60.f );
			glTexCoord2f(0.f,1.f); glVertex2f( -55.f, 60.f );
			glTexCoord2f(1.f,1.f); glVertex2f( 55.f, 60.f );
			glTexCoord2f(1.f,0.f); glVertex2f( 55.f, -60.f );
			glEnd();
			youwin.unbind();
		}

		SDL_GL_SwapBuffers();

		long diff = (SDL_GetTicks() - currentTime);
		if( diff < 15 )
			SDL_Delay( 15 - diff );
		
		lastTime = currentTime;
	}

	return running;
}
